# -*- coding: utf-8 -*-

import os

# python3
from pathlib import Path


def create_folder(file):
    """判断文件路径或文件夹是否存在，不存在就依次创建"""
    path = Path(file)
    if path.is_dir():  # 是文件夹
        folder = path
    else:
        folder = path.parent
        pass
    # parents=True依次创建中间缺失的多级文件夹
    # exist_ok=True文件夹存在跳过,不存在就创建
    folder.mkdir(parents=True, exist_ok=True)
    pass


def get_path():
    # 会根据执行python命令的路径不同而改变
    print('os.getcwd():', os.getcwd())

    print(os.path.curdir)
    print(os.path.pardir)
    print(os.path.sep)

    print('__file__:', __file__)
    print('os.path.abspath(__file__):', os.path.abspath(__file__))
    print('os.path.dirname(os.path.abspath(__file__)):', os.path.dirname(os.path.abspath(__file__)))

    print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    print(os.path.abspath(os.path.join(__file__, os.path.pardir, os.path.pardir)))

    pass


def use_path(file_path):
    path = Path(file_path)
    print(path.name)  # 名称+后缀
    print(path.stem)  # 名称
    print(path.suffix)  # 后缀

    print(path.parents)
    print(path.parent)

    print(path.parents[0] == path.parent)

    print(path.is_dir())
    print(path.is_file())
    print(path.exists())

    # 修改文件名称+后缀
    # path = path.with_name('name.txt')
    path = path.with_stem('name')
    path = path.with_suffix('.txt')
    print(path)
    print(path.exists())

    print(Path.cwd())
    print(Path.home())

    paths = Path.cwd().iterdir()
    for p in paths:
        print(p)
        pass
    pass


if __name__ == '__main__':
    file_path = './logs/1/1/file.log'
    # create_folder(file_path)

    get_path()

    # use_path(__file__)

    pass
